package dao

import (
	"fmt"
	"laohuo/model"
)

func FetchWares(page, pagesize uint) ([]*model.Ware, error) {
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	rows, err := db.Query("SELECT * FROM `wares` WHERE isdel=0 ORDER BY `time` DESC LIMIT ?,?", (page-1)*pagesize, pagesize)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}
	defer rows.Close()

	var ws []*model.Ware
	for rows.Next() {
		var w model.Ware
		var isdel uint8
		if err := rows.Scan(&w.Id, &w.Name, &w.Desc, &w.Time, &isdel); err != nil {
			continue
		}
		ws = append(ws, &w)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("数据解析失败: %v", err)
	}
	return ws, nil
}

func FetchWareById(id uint) (*model.Ware, error) {
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	row := db.QueryRow("SELECT * FROM `wares` WHERE `id`=? and `isdel`=0", id)
	if err := row.Err(); err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}

	var s = &model.Ware{}
	var isdel uint8
	if err := row.Scan(&s.Id, &s.Name, &s.Desc, &s.Time, &isdel); err != nil {
		return nil, fmt.Errorf("解析失败: %v", err)
	}

	return s, nil
}

func AddWares(w *model.Ware) error {
	db, err := connect()
	if err != nil {
		return err
	}
	defer db.Close()

	res, err := db.Exec("INSERT INTO `wares`(`name`, `desc`, `time`) VALUES(?, ?, ?)", w.Name, w.Desc, w.Time)
	if err != nil {
		return err
	}

	id, _ := res.LastInsertId()
	w.Id = uint(id)
	return nil
}

func DelWares(id uint) error {
	db, err := connect()
	if err != nil {
		return err
	}
	defer db.Close()

	if _, err := db.Exec("UPDATE `wares` SET isdel=1 WHERE `id`=?", id); err != nil {
		return err
	}
	return nil
}

func CountWares() (int, error) {
	db, err := connect()
	if err != nil {
		return 0, err
	}
	defer db.Close()

	var total int
	if err := db.QueryRow("SELECT COUNT(*) FROM `wares` WHERE `isdel`=0").Scan(&total); err != nil {
		return 0, err
	}
	return total, nil
}
